package com.manor.main.activity;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.SdkVersionUtils;
import com.manor.common.CommonAppConfig;
import com.manor.common.Constants;
import com.manor.common.HtmlConfig;
import com.manor.common.bean.ConfigBean;
import com.manor.common.http.CommonHttpUtil;
import com.manor.common.http.HttpCallback;
import com.manor.common.http.PitUtil;
import com.manor.common.mob.MobShareUtil;
import com.manor.common.mob.ShareData;
import com.manor.common.utils.ClickUtil;
import com.manor.common.utils.CommonUtil;
import com.manor.common.utils.DateFormatUtil;
import com.manor.common.utils.KLog;
import com.manor.common.utils.L;
import com.manor.common.utils.PictureSelectorUtils;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.StaIntentUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.common.utils.WordUtil;
import com.manor.main.R;
import com.orhanobut.logger.Logger;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.UrlSafeBase64;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ycbjie.webviewlib.X5WebUtils;
import com.ycbjie.webviewlib.X5WebView;

import org.json.JSONException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import static com.manor.common.activity.AbsActivity.lacksPermission;

/**
 * 个人中心的H5子页面
 */
@Route(path = RouteUtil.PC_WEB)
public class PcWebActivity extends AppCompatActivity {
    private static final String TAG = PcWebActivity.class.getSimpleName();
    @Autowired
    int pathTitle;
    @Autowired
    String h5EndUrl;

    private X5WebView webView;
    private TextView titleView;
    private ImageView btnBack;


    private List<LocalMedia> selectList = new ArrayList<>();
    private String mToken;
    UploadManager uploadManager;
    String urlKey = "";

    private MobShareUtil mMobShareUtil;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pc_web);
        initView();
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)
                .init();
//        StatusBarUtil.setTranslucent(this);
//        StatusBarUtil.setColor(this, getResources().getColor(R.color.white));
        init();
        qiniu();
    }

    private void initView() {
        webView = findViewById(R.id.web_view);
        titleView = findViewById(R.id.titleView);
        btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> onBackPressed());

    }

    private void qiniu() {
        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshold(1024 * 1024)
                //                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                //                .use(false)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                //                .zone(FixedZone.zone2)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);

    }

    private void init() {
        ARouter.getInstance().inject(this);
        h5EndUrl = getIntent().getStringExtra(Constants.WEB_URL);
        pathTitle = getIntent().getIntExtra(Constants.WEB_TITLE, 0);
        String title = "";
        switch (pathTitle) {
            case StaIntentUtil.ARISTOCRATIC_PRIVILEGE:
                title = WordUtil.getString(R.string.aristocratic_privilege);
                break;
            case StaIntentUtil.FLASH_TO_TALENT:
                title = WordUtil.getString(R.string.flash_to_talent);
                break;
            case StaIntentUtil.TWINKLE_SCHOOL:
                title = WordUtil.getString(R.string.twinkle_school);
                break;
            case StaIntentUtil.TASK_CENTER:
                title = WordUtil.getString(R.string.task_center);
                break;
            case StaIntentUtil.INVITE_FRIENDS:
                title = WordUtil.getString(R.string.invite_friends);
                break;
            case StaIntentUtil.VISITORS_RECORD:
                title = WordUtil.getString(R.string.visitors_record);
                break;
            case StaIntentUtil.RECOMMEND:
                title = WordUtil.getString(R.string.my_recommend);
                break;
            case StaIntentUtil.MY_EARNINGS:
                title = WordUtil.getString(R.string.my_earnings);
                break;
            case StaIntentUtil.QUICK_RECHARGE:
                title = WordUtil.getString(R.string.quick_recharge);
                break;
            case StaIntentUtil.PRIVACY_AGREEMENT:
                title = WordUtil.getString(R.string.privacy_agreement);
                break;
            case StaIntentUtil.REGISTRATION_AGREEMENT:
                title = WordUtil.getString(R.string.registration_agreement);
                break;
            case StaIntentUtil.CHARGING_SETTINGS:
                title = WordUtil.getString(R.string.charging_settings);
                break;
            case StaIntentUtil.VIP_EXPERIENCE:
                title = WordUtil.getString(R.string.vip_exp);
            case StaIntentUtil.LIVE_BODY_CHARGE:
                title = WordUtil.getString(R.string.pay_verfify);
                break;
            case StaIntentUtil.FEED_BACK:
                title = "意见反馈";
                break;
        }
        titleView.setText(title);

        String card2 = getCard(2);
        String card5 = getCard(5);


        //前2后5   token 加密
        String uid = CommonAppConfig.getInstance().getUid();
        String token = CommonAppConfig.getInstance().getToken();
        String encodedString = "";
        Logger.i("card2:" + card2 + "---card5:" + card5);
        encodedString = UrlSafeBase64.encodeToString((card2 + token + card5).getBytes());

        //清除cookie
        X5WebUtils.removeCookie(this);
        try {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 11) {
                getWindow()
                        .setFlags(//硬件加速
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
        }
        webView.addJavascriptInterface(new JsInterface(), "jsInterface");



        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                if (url.startsWith("weixin://wap/pay?") || url.startsWith("weixin") || url.startsWith("wechat")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new androidx.appcompat.app.AlertDialog.Builder(PcWebActivity.this)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                }
                return !(url.startsWith("http") || url.startsWith("https"));
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                KLog.e("Web#onPageFinished", s);
            }
        });

        //禁止长按显示菜单
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        if (pathTitle == StaIntentUtil.ARISTOCRATIC_PRIVILEGE) {
            webView.loadUrl(HtmlConfig.NOBLE_PRIVILEGES + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.FLASH_TO_TALENT) {
            webView.loadUrl(HtmlConfig.FLASH_MASTER + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.TWINKLE_SCHOOL) {
            webView.loadUrl(HtmlConfig.SDSCHOOL + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.TASK_CENTER) {
            webView.loadUrl(HtmlConfig.RWCENTER + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.INVITE_FRIENDS) {
            webView.loadUrl(HtmlConfig.YQFRIEND + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.VISITORS_RECORD) {
            webView.loadUrl(HtmlConfig.FANGKE + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.RECOMMEND) {
            webView.loadUrl(HtmlConfig.TUIJIAN + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.QUICK_RECHARGE) {
            webView.loadUrl(HtmlConfig.CHONGZHI + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.CHARGING_SETTINGS) {
            webView.loadUrl(HtmlConfig.SHOUFEISHEZHI + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.PRIVACY_AGREEMENT) {
            webView.loadUrl(CommonAppConfig.SERVER_HTML + HtmlConfig.LINK_PRIVATE + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.REGISTRATION_AGREEMENT) {
            webView.loadUrl(CommonAppConfig.SERVER_HTML + HtmlConfig.LINK_REGISTER + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.VIP_EXPERIENCE) {
            webView.loadUrl(CommonAppConfig.SERVER_HTML + HtmlConfig.LINK_EXPERIENCE + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.LIVE_BODY_CHARGE) {
            webView.loadUrl(CommonAppConfig.SERVER_HTML + HtmlConfig.LINK_AUTH_LIVE_BODY_CHARGE + "&uid=" + uid + "&token=" + encodedString);
        } else if (pathTitle == StaIntentUtil.NO_NULL_WEB) {
            webView.loadUrl(h5EndUrl);
            return;
        } else if (StringUtil.isNotEmpty(h5EndUrl)) {
            webView.loadUrl(CommonAppConfig.SERVER_HTML + "/" + h5EndUrl + "&uid=" + uid + "&token=" + encodedString);
            Logger.i("web访问地址：" + CommonAppConfig.SERVER_HTML + "/" + h5EndUrl + "&uid=" + uid + "&token=" + encodedString);
        }
    }


    //生成随机数
    public static String getCard(int i) {
        Random rand = new Random();//生成随机数
        String cardNnumer = "";
        for (int a = 0; a < i; a++) {
            cardNnumer += rand.nextInt(10);//生成6位数字
        }
        return cardNnumer;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
                //退出网页
            } else {
                handleFinish();
            }
        }
        return false;
    }

    public void handleFinish() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setResult(RESULT_OK);
            finishAfterTransition();
        } else {
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        try {
            if (webView != null) {
                webView.destroy();
                webView = null;
            }
        } catch (Exception e) {
            Log.e("X5WebViewActivity", e.getMessage());
        }
        super.onDestroy();
    }

    PictureSelectorUtils pictureSelectorUtils = new PictureSelectorUtils();

    public class JsInterface {
        /**
         * @JavascriptInterface 这个是一定要有的，否则不可以
         */
        @JavascriptInterface
        public void jsCallPhoto() {
            //            ToastUtil.show("调用相册");
            if (ClickUtil.canClick()) {
                pictureSelectorUtils.selectLocalImg(PcWebActivity.this, null, 1, 1,
                        new PictureSelectorUtils.IAddImageListener() {
                            @Override
                            public void onSelectedPictures(List<LocalMedia> list) {
                                selectList = list;
                                Logger.i("selectList---" + selectList.get(0).getCompressPath());
                                Logger.i("selectList---" + selectList.get(0).getPath());
                                if (!"".equals(selectList.get(0).getCompressPath())) {
                                    CommonHttpUtil.getUploadQiNiuToken(new HttpCallback() {
                                        @Override
                                        public void onSuccess(int code, String msg, String info) {
                                            if (code == 0) {
                                                Logger.i(info);
                                                String result = PitUtil.strGetFirst(info);

                                                mToken = JSON.parseObject(result).getString("token");
                                                L.e(TAG, "-------上传的token------>" + mToken);
                                                uploadQiNiuFile(mToken);
                                            }
                                        }
                                    });
                                }
                            }
                        });

            }
        }

        @JavascriptInterface
        public void SavePicture(String img) {
            KLog.e("SavePicture", img);
            if (ClickUtil.canClick(600)) {
                AndPermission.with(PcWebActivity.this)
                        .runtime()
                        .permission(Permission.WRITE_EXTERNAL_STORAGE)
                        .onGranted(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                if (!lacksPermission(PcWebActivity.this, Permission.WRITE_EXTERNAL_STORAGE)) {
                                    long time = System.currentTimeMillis();
                                    saveBitmap(base64ToPicture(img), time + ".JPEG");
                                }
                            }
                        })
                        .onDenied(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                for (int i = 0; i < data.size(); i++) {
                                    KLog.e("tag", data.get(i) + "");
                                    if (lacksPermission(PcWebActivity.this, Permission.WRITE_EXTERNAL_STORAGE)) {
                                        Toast.makeText(PcWebActivity.this,
                                                getResources().getString(R.string.permissions_w), Toast.LENGTH_SHORT).show();
                                        if (AndPermission.hasAlwaysDeniedPermission(PcWebActivity.this, data)) {
                                            showSettingDialog(PcWebActivity.this,
                                                    getResources().getString(R.string.permissions_w),
                                                    10);
                                        } else {
                                            SavePicture(img);
                                        }
                                        return;
                                    }

                                }

                            }
                        })
                        .start();


            }
        }

        public void showSettingDialog(Context context, String msg, final int requestCode) {
            String message = msg;
            new AlertDialog.Builder(context).setCancelable(false)
                    .setTitle(context.getResources().getString(com.manor.common.R.string.permissions_title))
                    .setMessage(message)
                    .setPositiveButton(com.manor.common.R.string.permissions_setting, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            setPermission(requestCode);
                        }
                    })
                    .show();
        }

        private void setPermission(int requestCode) {
            AndPermission.with(PcWebActivity.this).runtime().setting().start(requestCode);
        }

        @JavascriptInterface
        public void lookUserInfo(String userId) {
            Log.i("js调用Android", "lookUserInfo " + userId);
            UserCenterActivity.Companion.forward(PcWebActivity.this, userId);
        }

        /**
         * @param lat         维度
         * @param lng         经度
         * @param destination 目的地
         */
        @JavascriptInterface
        public void showMapDialog(double lat, double lng, String destination) {
            CommonUtil.Companion.getInstance().showMapDialog(PcWebActivity.this, lat, lng, destination);
        }

        /**
         * 调用返回
         */
        @JavascriptInterface
        public void androidBack() {
            Log.i("js调用Android", "调用Android返回");
            //            ToastUtil.show("js调用Android返回");
            //            onBackPressed();
            setResult(RESULT_OK);
            PcWebActivity.this.finish();
        }


        /**
         * 分享
         *
         * @param type 分享类型 QQ weixin
         * @param url  分享链接
         */
        @JavascriptInterface
        public void share(String type, String url) {
            Logger.i(type + "-----" + url);
            ConfigBean configBean = CommonAppConfig.getInstance().getConfig();
            ShareData data = new ShareData();
            data.setTitle(configBean.getVideoShareTitle());
            data.setDes(configBean.getVideoShareDes());
            data.setImgUrl(CommonAppConfig.getInstance().getUserBean().getAvatarThumb());
            //            String webUrl = HtmlConfig.MAKE_MONEY + mShareCode;
            String webUrl = url;
            data.setWebUrl(webUrl);
            if (mMobShareUtil == null) {
                mMobShareUtil = new MobShareUtil();
            }
            mMobShareUtil.execute(type, data, null);

        }

        /**
         * 分享文字内容
         *
         * @param dlgTitle
         *      分享对话框标题
         * @param subject
         *      主题
         * @param content
         *      分享内容（文字）
         */
        @JavascriptInterface
        public void sharePrimeval(String dlgTitle, String subject, String content) {
            shareText(dlgTitle, subject, content);
        }


    }

    public void shareWechatFriend(String content) {
        Context mContext = PcWebActivity.this;

        if (isInstallApp(mContext,PACKAGE_WECHAT)) {
            Intent intent = new Intent();
            ComponentName cop = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
            intent.setComponent(cop);
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra("android.intent.extra.TEXT", content);
//            intent.putExtra("sms_body", content);
            intent.putExtra("Kdescription", !TextUtils.isEmpty(content) ? content : "");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        } else {
            Toast.makeText(mContext, "您需要安装微信客户端", Toast.LENGTH_LONG).show();
        }
    }

    public  void shareQQ(String content) {
        Context mContext = PcWebActivity.this;
        if (isInstallApp(mContext,PACKAGE_MOBILE_QQ)) {
            Intent intent = new Intent("android.intent.action.SEND");
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
            intent.putExtra(Intent.EXTRA_TEXT, content);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity"));
            mContext.startActivity(intent);
        } else {
            Toast.makeText(mContext, "您需要安装QQ客户端", Toast.LENGTH_LONG).show();
        }
    }

    public static final String PACKAGE_WECHAT = "com.tencent.mm";
    public static final String PACKAGE_MOBILE_QQ = "com.tencent.mobileqq";
    public static final String PACKAGE_QZONE = "com.qzone";
    public static final String PACKAGE_SINA = "com.sina.weibo";

    // 判断是否安装指定app
    public static boolean isInstallApp(Context context, String app_package){
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pInfo = packageManager.getInstalledPackages(0);
        if (pInfo != null) {
            for (int i = 0; i < pInfo.size(); i++) {
                String pn = pInfo.get(i).packageName;
                if (app_package.equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 分享文字内容
     *
     * @param dlgTitle
     *      分享对话框标题
     * @param subject
     *      主题
     * @param content
     *      分享内容（文字）
     */
    private void shareText(String dlgTitle, String subject, String content) {
        if (content == null || "".equals(content)) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        if (subject != null && !"".equals(subject)) {
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        }

        intent.putExtra(Intent.EXTRA_TEXT, content);

        // 设置弹出框标题
        if (dlgTitle != null && !"".equals(dlgTitle)) { // 自定义标题
            startActivity(Intent.createChooser(intent, dlgTitle));
        } else { // 系统默认标题
            startActivity(intent);
        }
    }


    public Bitmap base64ToPicture(String imgBase64) {
        String a = imgBase64.substring(23);
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(a, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    /*
     * 保存文件，文件名为当前日期
     */
    public void saveBitmap(Bitmap bitmap, String bitName) {

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Camera/" + bitName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/" + bitName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
        // 发送广播，通知刷新图库的显示
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        ToastUtil.show("保存成功");


    }


    private void uploadQiNiuFile(String mToken) {
        String path = selectList.get(0).getCompressPath();
        if (StringUtil.isEmpty(path)){
            path = SdkVersionUtils.checkedAndroid_Q()? selectList.get(0).getAndroidQToPath():selectList.get(0).getPath();
        }

        uploadFile(path, new UploadListener() {
            @Override
            public void onUploadSuccess(String urlkey1) {
                KLog.e("uploadQiNiuFile#onUploadSuccess", urlkey1);
                if (urlkey1 != null) {
                    urlKey = urlkey1;
                    Logger.i("urlkey---" + urlkey1);
                    runOnUiThread(() -> webView.loadUrl("javascript:aaa('" + urlkey1 + "')"));
                }
            }

            @Override
            public void onUploadFail(Error error) {
                KLog.e("uploadQiNiuFile#onUploadFail", error.getMessage());
            }


        });
    }


    //上传单个文件
    public void uploadFile(final String filePath, final UploadListener uploadListener) {

        if (filePath == null)
            return;
        new Thread(() -> {
            if (uploadManager == null) {
                uploadManager = new UploadManager();
            }
            String name = "WEB_IMG_" + DateFormatUtil.getCurTimeString() + ".png";
            uploadManager.put(filePath, name, mToken,
                    (key, respInfo, jsonData) -> {

                        if (respInfo.isOK()) {
                            Logger.i("jsonData", jsonData.toString());
                            String url = "";

                            try {
                                urlKey = jsonData.getString("key");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            uploadListener.onUploadSuccess(urlKey);

                        } else {
                            Logger.i(respInfo.error);
                            uploadListener.onUploadFail(new Error("上传失败" + respInfo.error));
                        }
                    }, new UploadOptions(null, null, false,
                            (key, percent) -> {
                                //                                        progressbar.setProgress((int) (percent * 100));
                                new ProgressBar(PcWebActivity.this).isShown();
                            }, null));
        }).start();
    }

    //上传回调
    public interface UploadListener {
        void onUploadSuccess(String url);

        void onUploadFail(Error error);
    }

    /**
     * 设置电池条颜色
     */
    private void initAnimator() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.main_bg)
                .init();
    }


}
